/**
 * 
 */
package gpl.scotlandyard.android.controllers;

import gpl.scotlandyard.android.R;
import gpl.scotlandyard.android.activities.PathFinderActivity;
import gpl.scotlandyard.android.activities.SimpleTrackerActivity;
import gpl.scotlandyard.android.activities.SplashActivity;
import gpl.scotlandyard.android.services.MapLoaderService;
import gpl.scotlandyard.beans.basics.Node;
import gpl.scotlandyard.beans.basics.Player;
import gpl.scotlandyard.services.basics.BoardManagerBuilder;
import gpl.scotlandyard.utils.Config;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.prefs.InvalidPreferencesFormatException;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.AssetManager;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

/** @author Norbert */
public class SplashController extends BasicController {

  private static final String TAG = SplashController.class.toString();

  private static final SplashController INSTANCE = new SplashController();

  private BoardManagerBuilder builder;

  private SplashController() {
  }

  @Override
  public void onViewCreated() {
    Log.d(TAG, "created");
    builder = new BoardManagerBuilder();
    loadConfig();
    loadMap();
  }

  /**
   * 
   */
  public void playQuickTrackMode() {
    Player fugitive = new Player(getActivity().getText(R.string.kw_mr_x).toString());
    fugitive.setFugitive(true);
    builder.addFugitive(fugitive);
    SimpleTrackerController.getInstance().setBoardManager(builder.getRandomBoardManager());
    getActivity().startActivity(new Intent(getActivity(), SimpleTrackerActivity.class));
    getActivity().finish();
  }

  /**
   * 
   */
  public void playPathFinderMode() {
    Player fugitive = new Player(getActivity().getText(R.string.kw_mr_x).toString());
    fugitive.setFugitive(true);
    builder.addFugitive(fugitive);
    final EditText edit = new EditText(getActivity());
    edit.setSingleLine(true);
    edit.setHint(R.string.path_finder_detectives_hint);
    OnClickListener lstnr = new OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        String input = edit.getText().toString().trim();
        if (!"".equals(input)) {
          for (String names : input.split(" ")) {
            Player detective = new Player(names);
            builder.addDetective(detective);
          }
          PathFinderController.getInstance().setBoardManager(builder.getBoardManager());
          getActivity().startActivity(new Intent(getActivity(), PathFinderActivity.class));
          getActivity().finish();
        } else {
          Toast.makeText(getActivity(), R.string.path_finder_detectives_empty, Toast.LENGTH_LONG).show();
        }
      }
    };
    getDialogWithView(R.string.kw_detectives, edit, lstnr).create().show();
  }

  /** Loads configuration file. */
  private void loadConfig() {
    try {
      String file = getActivity().getString(R.string.file_conf);
      InputStream confStream = getActivity().getAssets().open(file, AssetManager.ACCESS_BUFFER);
      Config.load(confStream);
    } catch (IOException e) {
      Log.e(TAG, "impossible to load configuration : " + e.getLocalizedMessage());
      showErrorDialog(R.string.err_load_map);
      Log.e(TAG, "stop application");
      getActivity().finish();
    } catch (InvalidPreferencesFormatException e) {
      Log.e(TAG, "impossible to load configuration : " + e.getLocalizedMessage());
      showErrorDialog(R.string.err_load_map);
      Log.e(TAG, "stop application");
      getActivity().finish();
    }
  }

  /** Uses loader service to build the map. */
  private void loadMap() {
    Log.i(TAG, "no map loaded");
    MapLoaderService mapService = new MapLoaderService();
    mapService.addListener(new MapLoaderService.Listener() {
      @Override
      public void jobFinished(final ArrayList<Node> map) {
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Log.i(TAG, "job finished");
            builder.setMap(map);
            getActivity().showButtons();
          }
        });
      }

      @Override
      public void jobFailed(final Exception e) {
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Log.e(TAG, "impossible to load map : " + e.getLocalizedMessage());
            showErrorDialog(R.string.err_load_map);
            Log.e(TAG, "stop application");
            getActivity().finish();
          }
        });
      }
    });
    Log.i(TAG, "launch job");
    mapService.perform(getActivity().getAssets(), getActivity().getString(R.string.file_map));
  }

  /** @return the instance */
  public static SplashController getInstance() {
    return INSTANCE;
  }

  @Override
  public SplashActivity getActivity() {
    return (SplashActivity) super.getActivity();
  }

}
